﻿using DocumentFormat.OpenXml.Packaging;
using OpenXmlPowerTools;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Xml.Linq;

namespace Yz.Core.Tools
{
    public class YzWord
    {

        public static string ToHtml(string filePath)
        {
            byte[] array = File.ReadAllBytes(filePath);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                memoryStream.Write(array, 0, array.Length);
                WordprocessingDocument val = WordprocessingDocument.Open((Stream)memoryStream, true);
                try
                {
                    return ConvertToHtml(val);
                }
                finally
                {
                    ((IDisposable)val)?.Dispose();
                }
            }
        }

        public static string ConvertToHtml(WordprocessingDocument wDoc)
        { 
            int imageCounter = 0;
            string pageTitle = "";
            CoreFilePropertiesPart coreFilePropertiesPart = wDoc.CoreFilePropertiesPart;
            if (coreFilePropertiesPart != null)
            {
                pageTitle = (((string)PtOpenXmlExtensions.GetXDocument(coreFilePropertiesPart).Descendants(DC.title).FirstOrDefault()) ?? "");
            }
            WmlToHtmlConverterSettings settings = new WmlToHtmlConverterSettings()
            {
                AdditionalCss = "body { margin: 1cm auto; max-width: 20cm; padding: 0; }",
                PageTitle = pageTitle,
                FabricateCssClasses = true,
                CssClassPrefix = "pt-",
                RestrictToSupportedLanguages = false,
                RestrictToSupportedNumberingFormats = false
            };
           
            settings.ImageHandler = delegate (ImageInfo imageInfo)
                {
                    int num = ++imageCounter;
                    string a = imageInfo.ContentType.Split('/')[1].ToLower();
                    ImageFormat imageFormat = null;
                    if (a == "png")
                    {
                        imageFormat = ImageFormat.Png;
                    }
                    else if (a == "gif")
                    {
                        imageFormat = ImageFormat.Gif;
                    }
                    else if (a == "bmp")
                    {
                        imageFormat = ImageFormat.Bmp;
                    }
                    else if (a == "jpeg")
                    {
                        imageFormat = ImageFormat.Jpeg;
                    }
                    else if (a == "tiff")
                    {
                        a = "gif";
                        imageFormat = ImageFormat.Gif;
                    }
                    else if (a == "x-wmf")
                    {
                        a = "wmf";
                        imageFormat = ImageFormat.Wmf;
                    }
                    if (imageFormat == null)
                    {
                        return null;
                    }
                    string arg = null;
                    try
                    {
                        using (MemoryStream memoryStream = new MemoryStream())
                        {
                            imageInfo.Bitmap.Save((Stream)memoryStream, imageFormat);
                            byte[] inArray = memoryStream.ToArray();
                            arg = Convert.ToBase64String(inArray);
                        }
                    }
                    catch (ExternalException)
                    {
                        return null;
                    }
                    ImageFormat format = imageInfo.Bitmap.RawFormat;
                    ImageCodecInfo val4 = ImageCodecInfo.GetImageDecoders().First((ImageCodecInfo c) => c.FormatID == format.Guid);
                    string mimeType = val4.MimeType;
                    string value = $"data:{mimeType};base64,{arg}";
                    return new XElement(Xhtml.img, new XAttribute(NoNamespace.src, value), imageInfo.ImgStyleAttribute, (imageInfo.AltText != null) ? new XAttribute(NoNamespace.alt, imageInfo.AltText) : null);
                };
            XElement xElement = WmlToHtmlConverter.ConvertToHtml(wDoc, settings);
            XDocument xDocument = new XDocument(new XDocumentType("html", null, null, null), xElement);
            return xDocument.ToString(SaveOptions.DisableFormatting);
        }

    }
}
